const transform_tool = require("../utils/transform_tool");
const {
    whisper,
    info,
    getPrint,
    success,
    log,
    LogLevel,
} = require("../utils/log_tool");
const { pause } = require("../utils/interaction_tool");
const { BaseCommand } = require("./base");
const { eval_code } = require("./share_data");

class PrintCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const level = data?.level || LogLevel.INFO;
        let ignore = data?.ignore || [];
        ignore = transform_tool.toArray(ignore);
        let content = null;
        let use_content = false;
        const useRaw = level === LogLevel.STDOUT;
        if (
            data &&
            (data.mode === "content" || Object.hasOwn(data, "content"))
        ) {
            content = useRaw ? data.content : getPrint(data.content, true);
            use_content = true;
        } else if (
            data &&
            (data.mode === "code" || Object.hasOwn(data, "code"))
        ) {
            content = useRaw
                ? data.content
                : getPrint(eval_code(data.code), true);
            use_content = true;
        }
        if (use_content) {
            if (content && content.split("\n").length > 1) {
                log("");
            }
            log(content, undefined, level);
        } else {
            log("");
            let keys = data?.key
                ? transform_tool.toArray(data.key)
                : Object.keys(this.shareData);
            keys = keys.filter((key) => ignore.indexOf(key) === -1);
            // 仅显示最近的几条
            const numShowLatest = data?.count || keys.length;
            if (numShowLatest > 20) {
                await pause(`即将打印 ${numShowLatest} 条数据`);
            }
            for (
                let index = keys.length - numShowLatest;
                index < keys.length;
                index++
            ) {
                const key = keys[index];
                log(
                    useRaw
                        ? this.getDataByKey(key)
                        : `${key} => ${getPrint(this.getDataByKey(key), true)}`,
                    undefined,
                    level,
                );
            }
        }
    }
}

module.exports = {
    PrintCommand,
};
